#-*- coding:utf-8 -*-
import HTCUtils,time,hashlib
import urllib,urllib2
import json,datetime
import qcfg
#http格式字符
TimesAsHigh                     ='\x1C\x21\x78\x1B\x21\x50'                     #倍高字体
TimesAsHighBackToNormal         ='\x1C\x21\x70\x1B\x21\x40'                     #倍高字体 恢复正常
NormalCenter                    ='\x1B\x61\x31'                                 #正常居中
NormalCenterBackToNormal        ='\x1B\x61\x31'                                 #正常居中 恢复正常 左对齐
TimesAsHighCenter               ='\x1C\x21\x78\x1B\x21\x50\x1B\x61\x31'         #倍高居中
TimesAsHighCenterBackToNormal   ='\x1C\x21\x70\x1B\x21\x40\x1B\x61\x30'         #倍高居中 恢复正常
TimesAsWide                     ='\x1C\x21\x74\x1B\x21\x60'                     #倍宽字体
TimesAsWideBackToNormal         ='\x1C\x21\x70\x1B\x21\x40'                     #倍宽字体 恢复正常  
TimesAsWideCenter               ='\x1C\x21\x74\x1B\x21\x60\x1B\x61\x31'         #倍宽居中
TimesAsWideCenterBackToNormal   ='\x1C\x21\x70\x1B\x21\x40\x1B\x61\x30'         #倍宽居中 恢复正常
Large                           ='\x1C\x21\x7C\x1B\x21\x70'                     #大号字体
LargeBackToNormal               ='\x1C\x21\x70\x1B\x21\x40'                     #大号字体 恢复正常
LargeCenter                     ='\x1C\x21\x7C\x1B\x21\x70\x1B\x61\x31'         #大号居中
LargeCenterBackToNormal         ='\x1C\x21\x70\x1B\x21\x40\x1B\x61\x30'         #大号居中 恢复正常 左对齐
    
#    云 格式字符 注:<br自带换行效果>
    #"<BR>"为换行,"<CUT>"为切刀指令(主动切纸,仅限切刀打印机使用才有效果)
    #"<LOGO>"为打印LOGO指令(前提是预先在机器内置LOGO图片),"<PLUGIN>"为钱箱或者外置音响指令
    #成对标签：
    #"<CB></CB>"为居中放大一倍,"<B></B>"为放大一倍,"<C></C>"为居中,<L></L>字体变高一倍
    #</W>字体变宽一倍,"<QR></QR>"为二维码,"<BOLD></BOLD>"为字体加粗,"<RIGHT><\nIGHT>"为右对齐
 
####################################################################################################################
def YLW_YunPrinter_58(aStr_msg):
    dict     = YLW_msg_format(aStr_msg)
    content  = YLW_YunPrinter_58_format(dict)
    recv_msg = PushPrintMsg(acontent)
    return recv_msg
    
def YLW_YunPrinter_80(aStr_msg):
    #dict     = YLW_msg_format(aStr_msg)
    content  = PushDemo1()
    #recv_msg = PushPrintMsg(content)
    return " "

def YLW_HttpPrinter_80(aStr_msg):
    dict     = YLW_msg_format(aStr_msg)
    content  = YLW_HttpPrinter_80_format(dict)
    return msgDecode(content)

    
def PushDemo1():
    #IP = "http://api.feieyun.cn/Api/Open/"
    IP = "http://192.168.1.60:8080/cloud/"
    params = {'content':'hello'}
    #params = "stime=1480570274&content=nothing&sig=c0f50487d7e7288b583751c7c16df9acaf5ac275&sn=916503858&apiname=Open_printMsg&user=2225759935%40qq.com"
    encodedata = urllib.urlencode(params)
    req = urllib2.Request(url = IP,data =encodedata)
    #req = urllib2.Request(IP)
    rsp = urllib2.urlopen(req)
    return " "
    
ylw_58_lenth = 32    #小票所占字符
ylw_80_lenth = 32+15 #小票所占字符
first_msg    = 'MESSAGEBEGIN'  #标识 开头(云不需要)
#
def msgDecode(aMsg):
    return aMsg.decode('utf-8').encode('GB18030')
    

#填充空格
def getBlank(int):
    buf=''
    for a in range(int):
        buf=buf+' '
    return buf;
 
def YLW_HttpPrinter_80_format(dict):
    buf = TimesAsHighCenter + '欢迎光临' 
    buf +='\n' + TimesAsHighCenter + str(dict['mName']) + '\n' + TimesAsHighCenterBackToNormal
    buf += '\n单号:' + ' ' + str(dict['orderId'])
    buf += '\n'+'*' * ylw_80_lenth
    buf += '\n档口:' + ' ' + str(dict['sName'])
    #buf += '\n账号:' + ' ' + str(dict['aNumber'])
    buf += '\n卡号:' + ' ' + str(dict['card'])
    ltime=time.localtime(HTCUtils.timeUnix())
    timeStr=time.strftime("%Y-%m-%d %H:%M:%S", ltime)
    #buf += '\n\n时间:'   + getBlank(1) + str(dict['date']) + getBlank(1) + str(dict['time'])
    buf += '\n\n时间:'   + ' ' + timeStr
    buf += '\n' + '-' * ylw_80_lenth
    buf += '\n计价方式:'     + getBlank(ylw_80_lenth-(len(str(dict['vMethod']))*2/3) - len('数量件')) + str(dict['vMethod'])
    buf += '\n开始时间:'     + getBlank(ylw_80_lenth-len(str(dict['sTime']))         - len('数量件')) + str(dict['sTime'])
    buf += '\n结束时间:'     + getBlank(ylw_80_lenth-len(str(dict['eTime']))         - len('数量件')) + str(dict['eTime'])
    buf += '\n开始表数:'     + getBlank(ylw_80_lenth-len(str(dict['sValue']))        - len('数量件')) + str(dict['sValue'])
    buf += '\n结束表数:'     + getBlank(ylw_80_lenth-len(str(dict['eValue']))        - len('数量件')) + str(dict['eValue'])
    buf += '\n单价(元/分):'  + getBlank(ylw_80_lenth-len(str(dict['unit_s']))        - len('数量件键')) + str(dict['unit_s'])
    buf += '\n单价(元/吨):'  + getBlank(ylw_80_lenth-len(str(dict['unit_t']))        - len('数量件键')) + str(dict['unit_t'])
    buf += '\n用时(秒):'     + getBlank(ylw_80_lenth-len(str(dict['uTime']))         - len('数量件')) + str(dict['uTime'])
    buf += '\n使用字数:'     + getBlank(ylw_80_lenth-len(str(dict['uWeight']))       - len('数量件')) + str(dict['uWeight'])
    buf += '\n消费金额:'     + getBlank(ylw_80_lenth-len(str(dict['money']))         - len('数量件')) + str(dict['money'])
    buf += '\n'+'*' * ylw_80_lenth
    buf += '\n\n'+NormalCenter+'http://www.rcflat.com/'
    buf += '\n'+NormalCenter+'888-888-8888'+'\n'+'\n'+'\n'
    return first_msg+buf;  
   
def YLW_YunPrinter_80_format(dict):
#orderId:单号，mName：市场名称，aNumber：账号（手机号），payment:支付方式，date:日期，time:时间，
#bData:购买的数据[{fName:蔬菜名称，fWeight:重量，uPrice:单价,sTotal:小计}],
#tNumber:数量，tWeight:重量，yingPay,应付，save:节省，paid:实付
    buf = '<L><C>欢迎光临</C></L>'
    buf += '<BR><C><L>' + str(dict['mName']) + '</L></C>'
    buf += '<BR>单号:' + ' ' + str(dict['orderId'])
    buf += '<BR>***********************************************'
    buf += '<BR>档口:' + ' ' + str(dict['sName'])
    buf += '<BR>账号:' + ' ' + str(dict['aNumber'])
    buf += '<BR>卡号:' + ' ' + str(dict['card'])
    #buf += '<BR>计价方式:' + ' ' + str(dict['vMethod'])
    buf += '<BR><BR>时间:' + getBlank(1) + str(dict['date']) + getBlank(1) + str(dict['time'])
    #以下是对购买商品列表的遍历
    buf += '<BR>-----------------------------------------------'
    buf += '<BR>计价方式:' + getBlank(ylw_80_lenth-(len(str(dict['vMethod']))*2/3)   - len('数量件')) + str(dict['vMethod'])
    buf += '<BR>开始时间:' + getBlank(ylw_80_lenth-len(str(dict['sTime']))           - len('数量件')) + str(dict['sTime'])
    buf += '<BR>结束时间:' + getBlank(ylw_80_lenth-len(str(dict['eTime']))           - len('数量件')) + str(dict['eTime'])
    buf += '<BR>开始表数:' + getBlank(ylw_80_lenth-len(str(dict['sValue']))          - len('数量件')) + str(dict['sValue'])
    buf += '<BR>结束表数:' + getBlank(ylw_80_lenth-len(str(dict['eValue']))          - len('数量件')) + str(dict['eValue'])
    buf += '<BR>单价(元):' + getBlank(ylw_80_lenth-len(str(dict['unit']))            - len('数量件')) + str(dict['unit'])
    buf += '<BR>用时(秒):' + getBlank(ylw_80_lenth-len(str(dict['uTime']))           - len('数量件')) + str(dict['uTime'])
    buf += '<BR>使用字数:' + getBlank(ylw_80_lenth-len(str(dict['uWeight']))         - len('数量件')) + str(dict['uWeight'])
    buf += '<BR>消费金额:' + getBlank(ylw_80_lenth-len(str(dict['money']))           - len('数量件')) + str(dict['money'])
#    buf += '<BR>实付(元):' + getBlank(ylw_80_lenth-len(str(dict['paid']))              - len('数量件')) + str(dict['paid'])
    buf += '<BR>***********************************************'
    buf += '<BR><BR><C>'+'http://www.YLW.com/</C>'
    buf += '<C>888-888-8888</C>'
    return first_msg+buf;
    
    
#对数据的组合
def YLW_YunPrinter_58_format(dict):
    buf = '<L><C>欢迎光临</C></L>'
    buf += '<BR><C><L>'+ str(dict['mName']) + '</L></C>'
    buf += '<BR>单号:' + ' ' + str(dict['orderId'])
    buf += '<BR>********************************'
    buf += '<BR>档口:' + ' ' + str(dict['sName'])
    #buf += '<BR>账号:' + ' ' + str(dict['aNumber'])
    buf += '<BR>卡号:' + ' ' + str(dict['card'])
    ltime=time.localtime(HTCUtils.timeUnix())
    timeStr=time.strftime("%Y-%m-%d %H:%M:%S", ltime)
    #buf += '<BR><BR>时间:'   + getBlank(1) + str(dict['date']) + getBlank(1) + str(dict['time'])
    buf += '<BR><BR>时间:'   + ' ' + timeStr
    buf += '<BR>--------------------------------'
    buf += '<BR>计价方式:'   + getBlank(ylw_58_lenth-(len(str(dict['vMethod']))*2/3) - len('数量件')) + str(dict['vMethod'])
    buf += '<BR>开始时间:'   + getBlank(ylw_58_lenth-len(str(dict['sTime']))         - len('数量件')) + str(dict['sTime'])
    buf += '<BR>结束时间:'   + getBlank(ylw_58_lenth-len(str(dict['eTime']))         - len('数量件')) + str(dict['eTime'])
    buf += '<BR>开始表数:'   + getBlank(ylw_58_lenth-len(str(dict['sValue']))        - len('数量件')) + str(dict['sValue'])
    buf += '<BR>结束表数:'   + getBlank(ylw_58_lenth-len(str(dict['eValue']))        - len('数量件')) + str(dict['eValue'])
    buf += '<BR>单价(元/分):'   + getBlank(ylw_58_lenth-len(str(dict['unit_s']))          - len('数量件')) + str(dict['unit_s'])
    buf += '<BR>单价(元/吨):'   + getBlank(ylw_58_lenth-len(str(dict['unit_t']))          - len('数量件')) + str(dict['unit_t'])
    buf += '<BR>用时(秒):'   + getBlank(ylw_58_lenth-len(str(dict['uTime']))         - len('数量件')) + str(dict['uTime'])
    buf += '<BR>使用字数:'   + getBlank(ylw_58_lenth-len(str(dict['uWeight']))       - len('数量件')) + str(dict['uWeight'])
    buf += '<BR>消费金额:'   + getBlank(ylw_58_lenth-len(str(dict['money']))         - len('数量件')) + str(dict['money'])
    buf += '<BR>********************************'
    buf += '<BR><BR><C>'+'http://www.YLW.com/</C>'
    buf += '<C>888-888-8888</C>'
    return first_msg + buf;

def YLW_msg_format(aStr_msg):
    i = i.split("&v;")
    tmpMsg                   = {}
    tmpMsg["saleno"]         = i[0]
    tmpMsg["posid"]          = i[1]
    tmpMsg["p_num"]          = i[2]
    tmpMsg["start_tones"]    = i[3]
    tmpMsg["tones"]          = i[4]
    tmpMsg["seconds"]        = i[5]
    tmpMsg["start_time"]     = i[6]
    tmpMsg["stop_time"]      = i[7]
    tmpMsg["p_second"]       = i[8]
    tmpMsg["p_tones"]        = i[9]
    tmpMsg["pay_type"]       = i[10]
    tmpMsg["username"]       = i[11]
    tmpMsg["stop_way"]       = i[12]
    tmpMsg["card"]           = i[13]
    tmpMsg["su_card"]        = i[14]
    tmpMsg["stop_tones"]     = i[15]
    tmpMsg["money"]          = i[16]
    tmpMsg["be_money"]       = i[17]
    tmpMsg["af_money"]       = i[18]
    tmpMsg["phone"]          = i[19]
    tmpMsg["card_type"]      = i[20]
    tmpMsg["d_name"]         = i[21]
    tmpMsg["mac"]            = i[22]
    tmpMsg["mincharge"]      = i[23]
    tmpMsg["market_name"]    = qcfg.MARK_NAME
    tmpMsg["url"]            = 'WWW.YLWOK.COM'
    tmpMsg["hotline"]        = '400-888-8888'
    if arr[10] == '0' :
        tmpMsg['vMethod'] = "计时"
    if arr[10] == '1' :
        tmpMsg['vMethod'] = "计量"
    if arr[10] == '2' :
        tmpMsg['vMethod'] = "智能"
    return tmpMsg

    
def PushPrintMsg(acontent):
    PRINTER_SN = "916503858"
    #PRINTER_SN = "916800415"
    #飞鹅云后台注册用户名
    user ='2225759935@qq.com'
    #当前UNIX时间戳，10位，精确到秒。
    stime = str(HTCUtils.timeUnix())
    #飞鹅云后台UKEY
    UKEY ='Ww5jt539bQSFMyc6'
    #以UKEY作为密钥。算法：SHA1(user+UKEY+stime)， “+”号表示连接符
    sig= str((hashlib.sha1(user+UKEY+stime).hexdigest()))
    #请求的接口名称。Open_printMsg ：打印
    apiname="Open_printMsg"
    #打印机编号
    content = acontent
    #云地址
    IP = "http://api.feieyun.cn/Api/Open/"
    #需要对post进行拼装
    params = {'user':user,'stime':stime,'sig':sig,'apiname':apiname,'sn':PRINTER_SN,'content':content}
    encodedata = urllib.urlencode(params)
    req = urllib2.Request(url = IP,data =encodedata)
    res = urllib2.urlopen(req).read().decode('utf-8')
    #print "----feieyun response message----"
    #print res
    return res
